package com.jack.bookshop.util;

import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

import com.mchange.v2.c3p0.ComboPooledDataSource;

public class DatabaseUtil {

    static ComboPooledDataSource cpds = null;
    static Properties properties = null;
    // 读取数据库配置文件
    static final String FILE_PATH = "database.properties";
    static {
        cpds = new ComboPooledDataSource();
        properties = new Properties();
        try {
            InputStream in = DatabaseUtil.class.getClassLoader().getResourceAsStream(FILE_PATH);
            properties.load(in);
            cpds.setDriverClass(properties.getProperty("driverClassName"));
            cpds.setJdbcUrl(properties.getProperty("jdbcUrl"));
            cpds.setUser(properties.getProperty("user"));
            cpds.setPassword(properties.getProperty("password"));
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static Connection getConnection() {
        Connection conn = null;
        try {
            conn = cpds.getConnection();
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return conn;
    }

    public static void closeAll(ResultSet rs, Statement st, Connection conn) {
        if (rs != null) {
            try {
                rs.close();
            } catch (SQLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        if (st != null) {
            try {
                st.close();
            } catch (SQLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        if (conn != null) {
            try {
                conn.close();
            } catch (SQLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }

    // 测试数据库连接是否成功
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Connection conn = DatabaseUtil.getConnection();
        System.out.println(conn);
    }

}

